<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--搜索参数-->
      <el-col :span="20" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="业务名称" prop="userName">
            <el-input
              v-model="queryParams.formName"
              placeholder="请输入业务名称"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="创建者" prop="phonenumber">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入创建者"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="业务标签" prop="phonenumber">
            <el-input
              v-model="queryParams.tag"
              placeholder="请输入业务标签"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              >新建
            </el-button>
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
            :columns="columns"
          ></right-toolbar>
        </el-row>
        <el-table
          v-loading="loading"
          :data="formList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="表单名称"
            align="center"
            key="form.formName"
            prop="form.formName"
            v-if="columns[0].visible"
          />
          <el-table-column
            label="隶属部门"
            align="center"
            key="deptName"
            prop="deptName"
            v-if="columns[1].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="创建者名称"
            align="center"
            key="userName"
            prop="userName"
            v-if="columns[2].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="创建者昵称"
            align="center"
            key="nickName"
            prop="nickName"
            v-if="columns[3].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="标签"
            align="center"
            key="form.tags"
            v-if="columns[4].visible"
            :show-overflow-tooltip="true"
          >
            <template align="center" slot-scope="scope">
              <span
                v-for="(item, index) in scope.row.tagsArray"
                :key="(item, index)"
                ><el-tag>{{ item }}</el-tag
                >&#12288;</span
              >
            </template>
          </el-table-column>
          <el-table-column
            label="状态"
            align="center"
            key="status"
            v-if="columns[5].visible"
          >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.form.formStatus"
                :active-value=1
                :inactive-value=0
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            v-if="columns[6].visible"
            width="160"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.form.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNo"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <!-- 新建业务表单对话框 -->
    <el-dialog
      title="新建业务表单"
      :visible.sync="open"
      width="600px"
      append-to-body
    >
      <el-form
        ref="newFormDialog"
        :model="newFormDialog"
        :rules="newFormDialogRules"
        label-width="80px"
      >
        <el-row>
          <el-col :span="20">
            <el-form-item
              label="业务名称"
              prop="formInfo.formName"
              :rules="newFormDialogRules.formName"
            >
              <el-input
                v-model="newFormDialog.formInfo.formName"
                placeholder="请输入业务名称"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item
              label="归属部门"
              prop="formInfo.departmentId"
              :rules="newFormDialogRules.departmentId"
            >
              <treeselect
                v-model="newFormDialog.formInfo.departmentId"
                :options="deptOptions"
                :show-count="true"
                placeholder="请选择归属部门"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="备注">
              <el-input
                v-model="formInfo.formInfo"
                type="textarea"
                placeholder="请输入内容"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="标签">
              <el-button size="mini" @click="handleAddTag"> 添加标签</el-button>
              <div
                v-for="(item0, index0) in newFormDialog.tagsArray"
                :key="(item0, index0)"
              >
                <el-row>
                  <el-col :span="10">
                    <el-input v-model="newFormDialog.tagsArray[index0]" />
                  </el-col>
                  <br />
                </el-row>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <div
          v-for="(item, index) in newFormDialog.questions"
          :key="(item, index)"
        >
          <el-row>
            <el-col :span="50">
              <el-form-item
                :label="'业务' + (index + 1).toString()"
                :prop="`questions.${index}.questionName`"
                :rules="newFormDialogRules.questionName"
              >
                <el-input
                  v-model="item.questionName"
                  placeholder="请输入业务描述"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label="是否必须">
              <el-checkbox v-model="item.must"></el-checkbox>
            </el-form-item>
          </el-row>
          <el-row>
            <el-button type="primary" @click="addBlank(index + 1)" size="mini"
              >新增填空</el-button
            >
            <el-button type="primary" @click="addBlank(index + 1)" size="mini"
              >新增单选</el-button
            >
            <el-button type="primary" @click="addBlank(index + 1)" size="mini"
              >新增多选</el-button
            >
            <el-button type="primary" @click="addBlank(index + 1)" size="mini"
              >新增下拉</el-button
            >
            <el-button type="primary" @click="addBlank(index + 1)" size="mini"
              >新增时间范围</el-button
            >
            <el-button type="primary" @click="addBlank(index + 1)" size="mini"
              >新增时间</el-button
            ><br/><br/>
            <el-button type="primary" @click="addBlank(index + 1)" size="mini"
              >新增判断</el-button
            >
            <el-button type="primary" @click="addBlank(index + 1)" size="mini"
              >新增评分</el-button
            >
            <el-button type="primary" @click="addBlank(index + 1)" size="mini"
              >新增滑动</el-button
            >
          </el-row>
          <el-divider></el-divider>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">发 布</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { nanoid } from "nanoid";
import {
  listWork,
  changeStatus,
  publishForm,
  addBlank,
} from "@/api/flow/bussiness";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "User",
  dicts: ["sys_normal_disable", "sys_user_sex"],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 业务表格数据
      formList: null,
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 日期范围
      dateRange: [],
      newFormDialog: { formInfo: {}, questions: [], tagsArray: [] },
      // 表单参数
      formInfo: {},
      //表单题目
      questions: [],

      defaultProps: {
        children: "children",
        label: "label",
      },
      // 查询参数
      queryParams: {
        type: true,
        pageNo: 1,
        pageSize: 10,
        userName: undefined,
        deptIds: this.$store.state.user.deptids,
        formName: undefined,
        formStatus: undefined,
        tag: undefined,
      },
      // 列信息
      columns: [
        { key: 0, label: `表单名称`, visible: true },
        { key: 1, label: `隶属部门`, visible: true },
        { key: 2, label: `创建者名称`, visible: true },
        { key: 3, label: `创建者昵称`, visible: true },
        { key: 4, label: `标签`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `创建时间`, visible: true },
      ],
      // 表单校验
      newFormDialogRules: {
        formName: {
          required: true,
          message: "表单名称不能为空",
          trigger: "blur",
        },
        departmentId: {
          required: true,
          message: "归属部门不能为空",
          trigger: "blur",
        },
        questionName: {
          required: true,
          message: "问题不能为空",
          trigger: "blur",
        },
      },
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getList();
    this.getTreeselect();
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listWork(this.addDateRange1(this.queryParams, this.dateRange)).then(
        (response) => {
          console.log(response.forms);
          this.formList = response.forms;
          this.formList.forEach((item) => {
            this.$set(item, "tagsArray", []);
            if (item.form.tags != null) {
              item.tagsArray = item.form.tags.split(",");
            }
          });
          this.total = response.counts;
          this.loading = false;
        }
      );
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptIds = [data.id];
      this.handleQuery();
    },
    // 表单状态修改
    handleStatusChange(row) {
	  var params={
		formId:row.form.id,
		formStatus:row.form.formStatus == 1 ? 1 : 0,
	  }
      changeStatus(params).then(
        (response) => {
          console.log(response);
			this.$message({
			message: (row.form.formStatus == 1 ? "启用" : "禁用")+"表单成功",
			type: "success",
			});
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.newFormDialog.formInfo = {
        id: nanoid(),
        userId: this.$store.state.user.id,
        formName: "",
        formInfo: "",
        counts: 0,
        formStatus: 1,
        formUrl: "",
        createTime: null,
        timeLimit: null,
        beginTime: null,
        endTime: null,
        formPassword: null,
        ipLimit: null,
        isAnonymous: null,
        departmentId: null,
        tags: "",
        allCanSee: null,
      };
      this.newFormDialog.tagsArray = [];
      this.newFormDialog.questions = [];
      this.addBlank(0);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
    },
    /** 新增填空按钮操作 */
    addBlank(i) {
      var blank = {
        id: nanoid(),
        userId: this.$store.state.user.id,
        formId: this.newFormDialog.formInfo.id,
        orderId: ++this.newFormDialog.formInfo.counts,
        must: true,
        questionName: "",
        questionType: 0,
        questionInfo: "",
      };
      this.newFormDialog.questions.splice(i, 0, blank);
    },
    /** 新增标签选项 */
    handleAddTag() {
      this.newFormDialog.tagsArray.push("默认");
    },
    /** 发布按钮操作 */
    submitForm() {
      this.$refs["newFormDialog"].validate((valid) => {
        if (valid) {
          this.newFormDialog.formInfo.createTime = this.parseTime(new Date());
          //tagsArray字符串拼接
          for (var i = 0; i < this.newFormDialog.tagsArray.length; i++) {
            this.newFormDialog.formInfo.tags += this.newFormDialog.tagsArray[i];
            if (i != this.newFormDialog.tagsArray.length - 1) {
              this.newFormDialog.formInfo.tags += ",";
            }
          }
          var params = {
            formInfo: this.newFormDialog.formInfo,
            questions: this.newFormDialog.questions,
          };
          console.log(params);
          var params = {
            id: this.newFormDialog.formInfo.id,
            userId: this.newFormDialog.formInfo.userId,
            formName: this.newFormDialog.formInfo.formName,
            formInfo: this.newFormDialog.formInfo.formInfo,
            counts: this.newFormDialog.formInfo.counts,
            formStatus: this.newFormDialog.formInfo.formStatus,
            formUrl: this.newFormDialog.formInfo.formUrl,
            createTime: this.newFormDialog.formInfo.createTime,
            timeLimit: this.newFormDialog.formInfo.timeLimit,
            beginTime: this.newFormDialog.formInfo.beginTime,
            endTime: this.newFormDialog.formInfo.endTime,
            formPassword: this.newFormDialog.formInfo.formPassword,
            ipLimit: this.newFormDialog.formInfo.ipLimit,
            tags: this.newFormDialog.formInfo.tags,
            isAnonymous: this.newFormDialog.formInfo.isAnonymous,
            departmentId: this.newFormDialog.formInfo.departmentId,
            allCanSee: this.newFormDialog.formInfo.allCanSee,
          };
          //调用接口，新建表单
          publishForm(params)
            .then((response) => {
              console.log(response);
              this.$message({
                message: "新建业务型表单成功",
                type: "success",
              });
              for (var i = 0; i < this.newFormDialog.questions.length; i++) {
                var blank = {
                  id: this.newFormDialog.questions[i].id,
                  userId: this.newFormDialog.questions[i].userId,
                  formId: this.newFormDialog.questions[i].formId,
                  orderId: this.newFormDialog.questions[i].orderId,
                  must: this.newFormDialog.questions[i].must,
                  questionName: this.newFormDialog.questions[i].questionName,
                  questionType: this.newFormDialog.questions[i].questionType,
                  questionInfo: this.newFormDialog.questions[i].questionInfo,
                };
                console.log(blank);
                //调用接口，新建表单
                addBlank(blank)
                  .then((response) => {
                    console.log(response);
                  })
                  .catch((error) => {
                    console.log(error);
                  });
              }
              this.open = false;
            })
            .catch((error) => {
              console.log(error);
            });
        } else {
          return false;
        }
      });
    },
  },
};
</script>
